package com.yesallchina.wxapp.officialaccount.service;

import com.yesallchina.wxapp.officialaccount.config.WxOfficialAccountApiUrlProperties;
import com.yesallchina.wxapp.officialaccount.config.WxOfficialAccountCommonProperties;
import com.yesallchina.wxapp.officialaccount.config.WxOfficialAccountSpiProperties;
import com.yesallchina.wxapp.officialaccount.context.SpringApplicationContext;
import com.yesallchina.wxapp.officialaccount.ext.ConfigLoader;
import org.springframework.beans.factory.InitializingBean;

public class WxOfficialAccountInitializer implements InitializingBean {

    private SpringApplicationContext appCtx;

    private WxOfficialAccountCommonProperties commonProp;

    private WxOfficialAccountSpiProperties spiProp;

    private WxOfficialAccountApiUrlProperties apiProp;


    public WxOfficialAccountInitializer(SpringApplicationContext appCtx, WxOfficialAccountCommonProperties commonProp, WxOfficialAccountSpiProperties spiProp, WxOfficialAccountApiUrlProperties apiProp) {
        this.appCtx = appCtx;
        this.commonProp = commonProp;
        this.spiProp = spiProp;
        this.apiProp = apiProp;
    }

    public WxOfficialAccountCommonProperties getCommonProp() {
        return commonProp;
    }

    public WxOfficialAccountSpiProperties getSpiProp() {
        return spiProp;
    }

    public WxOfficialAccountApiUrlProperties getApiProp() {
        return apiProp;
    }

    public SpringApplicationContext getAppCtx() {
        return appCtx;
    }

    private void loadCommonConfig(){
        try {
            String tarClass = spiProp.getCommonConfigLoaderName();
            ConfigLoader<WxOfficialAccountCommonProperties> loader = appCtx.getBean(tarClass);
            if (loader != null) {
                this.commonProp = loader.load();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        loadCommonConfig();
    }
}
